package controllers;

import net.ufrog.common.utils.Strings;
import net.ufrog.common.weixin.APIs;
import play.Logger;
import play.Play;
import play.mvc.Controller;
import weixin.WXMessage;
import weixin.processer.message.WXMessageProcesser;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * 服务控制器<br>
 * 提供微信服务
 * 
 * @author ultrafrog
 * @version 1.0, 2014-11-04
 * @since 1.0
 */
public class Server extends Controller {

	/**
	 * 校验签名
	 * 
	 * @param timestamp
	 * @param nonce
	 * @param signature
	 * @param echostr
	 */
	public static void check(String timestamp, String nonce, String signature, String echostr) {
		if (Strings.empty(timestamp)) return;
		if (APIs.checkSignature(Play.configuration.getProperty("application.token"), timestamp, nonce, signature)) {
			renderText(echostr);
		}
	}
	
	/** 处理消息 */
	public static void message() {
		WXMessage wxmsg = WXMessage.fromInputStream(request.body);
		WXMessage bkmsg = new WXMessage(wxmsg.fromUserName, wxmsg.toUserName);
		WXMessageProcesser.doProcess(wxmsg, bkmsg);
		
		// 返回消息
		if (!Strings.empty(bkmsg.msgType)) {
			XStream xstream = new XStream(new DomDriver());
			xstream.processAnnotations(WXMessage.class);
			String xml = xstream.toXML(bkmsg);
			Logger.debug("response xml: %s", xml);
			renderText(xml);
		}
	}
}
